import Vue from 'vue'
import VueRouter from 'vue-router'
import NProgress from "nprogress"; // 导入 nprogress模块
import "nprogress/nprogress.css"; // 导入样式，否则看不到效果
NProgress.configure({ showSpinner: true }); // 显示右上角螺旋加载提示

import { getToken } from '@/utils/auth'

import { constantRoutes } from './router.config.js'
import { componentRoutes } from './router.component.js'
Vue.use(VueRouter)
//添加以下代码   // 频繁点击路由不会报错
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

const createRouter = () =>
    new VueRouter({
      routes: [...constantRoutes, ...componentRoutes] // []   js  css html
    })

const router = createRouter();
//  访问白名单  访问的时候可以直接放行
const whiteList = ['/loginFirst', '/goRegister','/index', '/user/profile', '/redirect', '/user/update','/user/virtual','/user/virtual/list',
    '/user/canvas','/user/index','/trader/bunkEdit', '/trader/traderList','/trader/brandList', '/base/systemSetting',
    '/role/index', '/menu/index', '/logininfor/index', '/notice/index',  '/index/index',
    '/product/productStopList', '/product/productType',
    '/report/purchaseStatistics', '/report/bunkStatistics', '/report/sellMonthStatistics', '/report/sellAreaStatistics',
    '/purchase/purchaseDetailList','/purchase/purchaseList', '/purchase/purchaseSupplier',
    '/stock/stockInList', '/stock/stockList','/stock/stockOutList','/stock/stockDetailList','/stock/stockInDetailList',
    '/stock/stockBadList', '/stock/stockOutDetailList', '/product/productList', '/product/productTypes',
    '/sell/sellList', '/sell/sellReturnDetailList']

router.beforeEach((to, from, next) => {
    // alert(to.fullPath)
    // alert(getToken());

    NProgress.start()   // 开启进度条
    if (getToken()) {
        if (to.path === '/loginFirst') {
            next({ path: '/' })   // 进入index首页
            NProgress.done()    // 完成进度条
        } else {
            next();
            NProgress.done()    // 完成进度条
        }
    } else {
        // 没有token
        if (whiteList.indexOf(to.path) !== -1) {
            // 在免登录白名单，直接进入
            next()
            NProgress.done();
        } else {
            // next(`/loginFirst?redirect=${to.fullPath}`) // 否则全部重定向到登录页
            let str = /^[0-9]*$/
            let s = to.path.slice(-(to.path.length -15));
            // alert(s)
            if (s !== '' &&- s !== undefined && str.test(s)){    //  判断是否到goRegister.vue
                next();   // 放行
            }else {
                next('/loginFirst');
            }
            // next();   //  直接跳到index
            NProgress.done();
        }
    }
})


export default router;
